import json
import os
import uuid

from global_config import *
from scripts import db_utils
from scripts.jianying.draft_config import *
from ui.widgets.notice_dialog import ConfirmDialog


# 写入剪映草稿
def sycn_draft():
    draft_json = None
    draft_content_path = None
    file = f'{root}\\setting_jianying_dir'
    if not os.path.exists(file):
        ConfirmDialog('提示', '未设置剪映草稿路径').get_result()
        return
    with open(file, 'r') as file:
        jianying_path = file.read()
        if jianying_path == '':
            ConfirmDialog('提示', '未设置剪映草稿路径').get_result()
            return
        jianying_path = f'{jianying_path}\\{get_cur_project()}'
        if not os.path.exists(jianying_path):
            ConfirmDialog('提示', '剪映草稿和项目名称不一致，找不到草稿').get_result()
            return
        # 草稿数据文件，json格式
        draft_content_path = f'{jianying_path}\\{draft_content_name}'
        with open(draft_content_path, 'r', encoding='utf-8') as file:
            draft_json = json.load(file)

    storyboards = db_utils.read_workflow(get_storyboards_path())

    if draft_json is None: return

    tracks_json: list = draft_json[key_tracks]

    # 检查json_array中是否存在目标id
    track_item = any(item["id"] == key_tracks_id for item in tracks_json)
    # 新建track
    if not track_item:
        with open('./scripts/jianying/track_item.json', 'r') as file:
            track_item = json.load(file)
            tracks_json.append(track_item)
    else:
        for item in tracks_json:
            if item["id"] == key_tracks_id:
                track_item = item
                break

    track_item['segments'] = []
    videos_json = draft_json[key_materials]['videos']
    canvases_json = draft_json[key_materials]['canvases']

    image_root = sorted([int(v) for v in os.listdir(get_workflows_img_dir())])
    svd_root = sorted([int(v) for v in os.listdir(get_workflows_svd_dir())])
    if '.DS_Store' in image_root:
        image_root.remove('.DS_Store')
    for index, board in enumerate(storyboards):
        inner_dir = os.path.join(get_workflows_img_dir(), str(image_root[index]))
        templist = os.listdir(inner_dir)
        if len(templist) == 0: continue
        imagefile = templist[0]

        svdfile = None
        svd_dir = None
        if len(svd_root) > 0:
            svd_dir = os.path.join(get_workflows_svd_dir(), str(svd_root[index]))
            templist = os.listdir(svd_dir)
            svdfile = templist[0] if len(templist) > 0 else None
            if svdfile is not None:
                imagefile = svdfile

        video_id = str(uuid.uuid4())

        draft_meta_content_path = f'{jianying_path}/{draft_meta_content_name}'
        with open(draft_meta_content_path, 'r+', encoding='utf-8') as filemeta:
            meta_draft_json = json.load(filemeta)
            draft_materials = meta_draft_json['draft_materials']
            if len(draft_materials) > 0:
                draft_materials = draft_materials[0]
            mater_values = draft_materials['value']
            if any(item['extra_info'] != imagefile for item in mater_values):
                # 新建matermal
                with open('./scripts/jianying/materials_item.json', 'r', encoding='utf-8') as file1:
                    value_item = json.load(file1)
                    value_item['extra_info'] = imagefile
                    value_item['metetype'] = 'photo' if svdfile is None else 'video'
                    value_item['file_Path'] = os.path.join(inner_dir if svdfile is None else svd_dir, imagefile)
                    value_item['id'] = str(uuid.uuid4())

                    mater_values.append(value_item)
                filemeta.seek(0)
                filemeta.flush()
                filemeta.write(json.dumps(meta_draft_json, ensure_ascii=False))

        # key_value.json
        # materialId = str(uuid.uuid4())
        # draft_key_value_path = f'{jianying_path}/{draft_key_value_name}'
        # with open(draft_key_value_path, 'r+', encoding='utf-8') as filekeyvalue:
        #     key_value_json = json.load(filekeyvalue)
        #     # 新建matermal
        #     with open('./source/jianying/key_value_item.json', 'r') as file1:
        #         value_item = json.load(file1)
        #         value_item['materialName'] = imagefile
        #         value_item['materialId'] = materialId
        #
        #         key_value_json[materialId] = value_item
        #     filekeyvalue.seek(0)
        #     filekeyvalue.flush()
        #     filekeyvalue.write(json.dumps(key_value_json))

        # 新建video
        with open('./scripts/jianying/video_item.json', 'r', encoding='utf-8') as file:
            video_item = json.load(file)
            video_item['material_name'] = imagefile
            video_item['path'] = os.path.join(inner_dir if svdfile is None else svd_dir, imagefile)
            video_item['type'] = 'photo' if svdfile is None else 'video'
            # video_item['height']
            # video_item['width']
            # video_item['video']
            video_item['id'] = video_id

            videos_json.append(video_item)

        # 新建segments
        with open('./scripts/jianying/segment_item.json', 'r', encoding='utf-8') as file:
            segment_item = json.load(file)

            # 新建canvases
            with open('./scripts/jianying/canvases_item.json', 'r', encoding='utf-8') as file:
                canvases_item = json.load(file)
                canvases_item['id'] = str(uuid.uuid4())
                canvases_item['blur'] = 0.375
                canvases_item['type'] = 'canvas_blur'  # 默认'none'
                canvases_json.append(canvases_item)
                segment_item['extra_material_refs'].append(canvases_item['id'])

            start = int(board.start * 1000 * 1000)
            duration = board.end * 1000 * 1000 - start
            if index + 1 < len(storyboards):
                next = storyboards[index + 1]
                tempdur = next.start * 1000 * 1000 - start
                duration = tempdur

            segment_item['source_timerange']['start'] = 0
            segment_item['source_timerange']['duration'] = duration
            segment_item['target_timerange']['start'] = board.start * 1000 * 1000
            segment_item['target_timerange']['duration'] = duration

            segment_item['material_id'] = video_id
            segment_item['id'] = str(uuid.uuid4())

            with open('./scripts/jianying/key_frames_item.json', 'r', encoding='utf-8') as file:
                keyframes_item = json.load(file)
                keyframes_item['id'] = str(uuid.uuid4())
                key_list = keyframes_item['keyframe_list']
                for index, item in enumerate(key_list):
                    item['id'] = str(uuid.uuid4())
                    if index == 0:
                        item['time_offset'] = 0
                    if index == 1:
                        item['time_offset'] = int(duration)
                segment_item['common_keyframes'] = [keyframes_item]
            track_item['segments'].append(segment_item)

    draft_content_path = f'{jianying_path}\\{draft_content_name}'
    with open(draft_content_path, 'w', encoding='utf-8' ) as file:
        file.write(json.dumps(draft_json, ensure_ascii=False))

    # 插入图片
    ConfirmDialog('提示', '剪映草稿保存成功').get_result()
    return None
